<template>
  <section>
    <el-card shadow="never">
      <div slot="header">
        {{ $t("user.settings") }}
      </div>
      <div class="columns">
        <div class="column is-full">
          <el-tabs v-model="activeName">
            <el-tab-pane :label="$t('user.info')" name="first">
              <el-form
                :label-position="labelPosition"
                label-width="100px"
                :model="user"
                ref="user"
              >
                <el-form-item :label="$t('user.account')">
                  <el-input v-model="user.username" disabled />
                </el-form-item>
                <el-form-item
                  :label="$t('user.name')"
                  prop="alias"
                  :rules="[
                    {
                      required: true,
                      message: this.$t('user.blankAlias'),
                      trigger: 'blur',
                    },
                    {
                      max: 20,
                      message: this.$t('user.errAlias'),
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input 
                  v-model="user.alias" 
                  @blur="user.alias=$event.target.value.trim()"
                  />
                </el-form-item>
                <el-form-item :label="$t('user.bio')">
                  <el-input 
                  v-model="user.bio" 
                  @blur="user.bio=$event.target.value.trim()"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')">{{
                    $t("user.submit")
                  }}</el-button>
                  <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane :label="$t('user.password')" name="second">
              <el-form
                :label-position="labelPosition"
                label-width="180px"
                status-icon
                :model="password"
                :rules="rules"
                ref="password"
              >
                <el-form-item
                  :label="$t('user.oldPassword')"
                  prop="oldPassword"
                >
                  <el-input v-model="password.oldPassword" type="password" />
                </el-form-item>
                <el-form-item
                  :label="$t('user.newPassword')"
                  prop="newPassword"
                >
                  <el-input v-model="password.newPassword" type="password" />
                </el-form-item>
                <el-form-item
                  :label="$t('Register.password2')"
                  prop="checkPassword"
                >
                  <el-input v-model="password.checkPassword" type="password" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="update_password">{{
                    $t("user.submit")
                  }}</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane :label="$t('user.avatar')" name="third">
              <div class="center">
                <div
                  class="image"
                  style="width: 200px; height: 200px; margin-bottom: 2em"
                >
                  <img :src="user.avatar" />
                </div>
              </div>
              <CutPortrait
                :upload-url="UploadUrl"
                @getUrl="getUrl"
                v-bind:username="this.user.username"
              ></CutPortrait>
            </el-tab-pane>
            <el-tab-pane :label="$t('user.email')" name="fourth">
              <el-form
                ref="ruleEmail"
                :model="ruleEmail"
                label-width="150px"
                class="demo-dynamic"
              >
                <el-form-item
                  prop="email"
                  :label="$t('user.email')"
                  :rules="[
                    {
                      required: true,
                      message: this.$t('user.blankEmail'),
                      trigger: 'blur',
                    },
                    {
                      type: 'email',
                      message: this.$t('user.errEmail'),
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input v-model="ruleEmail.email" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="update_email">{{
                    $t("user.submit")
                  }}</el-button>
                  <!-- <el-button @click="resetForm('dynamicValidateForm')">重置</el-button> -->
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <!-- <el-tab-pane :label="$t('user.phone')" name="fifth">
              <el-form
                ref="dynamicValidateForm"
                :model="user"
                label-width="150px"
                class="demo-dynamic"
              >
                <el-form-item :label="$t('user.phone')">
                  <el-input v-model="user.mobile" />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitForm('dynamicValidateForm')"
                    >{{ $t("user.submit") }}</el-button
                  >
                </el-form-item>
              </el-form>
            </el-tab-pane> -->
          </el-tabs>
        </div>
      </div>
    </el-card>
  </section>
</template>

<script>
import {
  getInfo,
  update,
  updatePassword,
  checkUserPassword,
  updateEmail,
} from "@/api/user";
import CutPortrait from "./CutPortrait";
import { getToken } from "@/util/auth";
export default {
  name: "Setting",
  components: {
    CutPortrait,
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value == "") {
        callback(new Error(this.$t("Register.rePass")));
      } else if (value != this.password.newPassword) {
        callback(new Error(this.$t("Register.matchPass")));
      } else {
        callback();
      }
    };

    var validateUserPassword = (rule, value, callback) => {
      //检查密码是否正确
      checkUserPassword(this.user.username, this.password.oldPassword).then(
        (resp) => {
          if (resp == 0) {
            callback(new Error("密码错误"));
          } else {
            callback();
          }
        }
      );
    };
    return {
      activeName: "first",
      labelPosition: "right",
      user: {
        id: "",
        username: "",
        alias: "",
        bio: "",
        email: "",
        mobile: "",
        avatar: "",
      },
      password: {
        oldPassword: "",
        newPassword: "",
        checkPassword: "",
      },
      ruleEmail: {
        email: "",
      },
      rules: {
        oldPassword: [
          {
            required: true,
            message: this.$t("user.blankOldPassword"),
            trigger: "blur",
          },
          {
            min: 6,
            max: 20,
            message: this.$t("user.errPassword"),
            trigger: "blur",
          },
          { validator: validateUserPassword, trigger: "blur" },
        ],
        newPassword: [
          {
            required: true,
            message: this.$t("user.blankNewPassword"),
            trigger: "blur",
          },
          {
            min: 6,
            max: 20,
            message: this.$t("user.errPassword"),
            trigger: "blur",
          },
        ],
        checkPassword: [
          {
            required: true,
            message: this.$t("Register.checkPassword"),
            trigger: "blur",
          },
          {
            validator: validatePass,
            trigger: "blur",
          },
        ],
      },
      ruleEmail: {
        email: "",
      },
      UploadUrl: process.env.VUE_APP_SERVER_URL + "/user/upload_avatar",
      imgPath: "", // 裁剪好的头像
    };
  },
  created() {
    this.fetchInfo();
  },
  methods: {
    fetchInfo() {
      getInfo(this.$route.params.username).then((res) => {
        const { data } = res;
        this.user = data;
        this.ruleEmail.email = this.user.email;
      });
    },
    submitForm(formName) {
      this.$refs.user.validate((valid) => {
        if (valid) {
          const formUser = {
            id: this.user.id,
            username: this.user.username,
            alias: this.user.alias,
            bio: this.user.bio,
          };
          update(formUser).then((res) => {
            this.$message.success(this.$t("user.success"));
            this.fetchInfo();
          });
        } else {
          this.$message.error(this.$t("user.errInfo"));
        }
      });
    },

    update_password() {
      this.$refs.password.validate((valid) => {
        if (valid) {
          updatePassword(
            this.user.username,
            this.password.oldPassword,
            this.password.newPassword
          ).then((resp) => {
            this.$message.success(this.$t("user.success"));
            this.$store.dispatch("user/logout").then(() => {
              this.$router.push({ path: this.redirect || "/" });
            });
          });
        } else {
          this.$message.error(this.$t("user.checkPassword"));
        }
      });
    },
    update_email() {
      this.$refs.ruleEmail.validate((valid) => {
        if (valid) {
          updateEmail(this.user.username, this.ruleEmail.email).then((resp) => {
            let { code, message } = resp;
            if (code === 200) {
              this.$message.success(this.$t("user.success"));
              this.fetchInfo();
            } else {
              this.$message.error(this.$t("user.sameEmail"));
            }
          });
        }
      });
    },
    getUrl(path) {
      this.imgPath = path;
      this.user.avatar = path;
    } /* ,
    resetForm(formName) {
      this.$refs[formName].resetFields()
    } */,
  },
};
</script>

<style scoped>
</style>